package remote

import (
	"apedge/pkg/configs"
	"apedge/pkg/protocol"
	"encoding/json"
	"fmt"
	"net/http"
	"time"

	"github.com/mitchellh/mapstructure"
)

type GetFileLocResp struct {
	Location     string `json:"location"`
	DownloadLink string `json:"downloadLink"`
}

func GetFileLocation(objectName string) (GetFileLocResp, error) {
	var getResourceRsp GetFileLocResp
	var client = &http.Client{
		Timeout: time.Second * 10,
	}

	getFileLocUrl := fmt.Sprintf("http://%s%s?modId=%s&objectName=%s", configs.Config.Relevant.Service.FileServerSvc, FileServerApi, configs.Config.Relevant.ModId, objectName)
	req, err := http.NewRequest("GET", getFileLocUrl, nil)
	if err != nil {
		return getResourceRsp, err
	}
	resp, err := client.Do(req)
	if err != nil {
		return getResourceRsp, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		return getResourceRsp, fmt.Errorf("file svc error %d %+v", resp.StatusCode, resp.Body)
	}

	var respBody protocol.APISuccessRsp
	err = json.NewDecoder(resp.Body).Decode(&respBody)
	if err != nil {
		return getResourceRsp, err
	}

	if respBody.Code != 0 {
		return getResourceRsp, fmt.Errorf("aom svc error %d %+v", respBody.Code, respBody.Msg)
	}
	logger.Infoln("-----------------------")

	err = mapstructure.Decode(respBody.Data, &getResourceRsp)
	if err != nil {
		return getResourceRsp, err
	}

	logger.Infof("res: %+v", getResourceRsp)
	return getResourceRsp, nil
}
